package com.nulldev.util.networking.rudp.demo;

import java.util.UUID;
import java.util.concurrent.atomic.LongAdder;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.util.random.GlobalRandom;
import com.nulldev.util.VariableAPI.util.random.nRandom;
import com.nulldev.util.data.variable;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.networking.ip.IP;
import com.nulldev.util.networking.rudp.Client;
import com.nulldev.util.networking.rudp.Connection;
import com.nulldev.util.networking.rudp.DataReceivedListener;
import com.nulldev.util.networking.rudp.Message;
import com.nulldev.util.networking.rudp.Server;
import com.nulldev.util.networking.rudp.util.SerializationUtils;

public class UDP2Demo {

	public static void main(String[] args) {
		Arguments.setup(new String[]
			{ "--rUDP.useNativeSerialization" });
		JVM.println("Using NT_API: " + SerializationUtils.USE_NT_API);
		final int port = IP.nextFreePort(9000, 13000);
		final Server s = new Server(port, "localhost", 32);
		s.startServer();
		final variable<Long> t = new variable<Long>(0L);
		s.registerServerListener(new DataReceivedListener() {

			final LongAdder adder = new LongAdder();

			@Override
			public void receivedMessage(Message message, final Connection connection) {
				adder.add(message.getData().length);
				JVM.println("downloaded: " + FileUtil.convertToStringRepresentation(adder.sum()));
			}

			@Override
			public void disconnected(UUID connectionId) {
			}

			@Override
			public void connected(Connection connection) {

			}
		});
		final Client c = new Client(port, "localhost");
		c.startClient();
		final nRandom nr = (nRandom) GlobalRandom.getFallbackRandom();
		while (true) {
			final byte[] payload = nr.bytes(8192);
			t.set(System.currentTimeMillis());
			c.sendUnreliableData(payload);
		}
	}

}
